/* Copyright (C)
 * 2017 - Xianlee.Wu  xianleewu@163.com
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 *
 */

#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <netdb.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <unistd.h>
#include <curl/curl.h>
#include "lewei_upload.h"

int lewei_global_init()
{
    curl_global_init(CURL_GLOBAL_ALL);

    return 0;
}

int lewei_global_deinit()
{
    curl_global_cleanup();

    return 0;
}

int lewei_format_data(char* buf, int len, const char* device_name, int value)
{
    snprintf(buf, len, LEWEI_POST_DATA_FORMAT, device_name, value);

    return 0;
}

int lewei_do_post(int gateway_num, const char* userkey, const char* data, int len)
{
    char curl_dst[LEWEI_POST_URL_MAX_LEN] = {0};
    char curl_header[LEWEI_USER_KEY_MAX_LEN] = {0};
    struct curl_slist * chunk = NULL;
    CURL* curl = NULL;
    CURLcode ret;

    snprintf(curl_dst, LEWEI_POST_URL_MAX_LEN, "%s%02d", LEWEI_GATEWAY, gateway_num);
    snprintf(curl_header, LEWEI_USER_KEY_MAX_LEN, "userkey:%s", userkey);
    curl = curl_easy_init();

    if(NULL == curl) {
        printf("%s %d:Do post failed!\n", __func__, __LINE__);
        return -1;
    }

    chunk = curl_slist_append(chunk, userkey);
    curl_easy_setopt(curl, CURLOPT_HTTPHEADER, chunk);
    curl_easy_setopt(curl, CURLOPT_URL, curl_dst);
    curl_easy_setopt(curl, CURLOPT_POSTFIELDS, data);
    curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, len);
    curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L);
    ret = curl_easy_perform(curl);
    curl_easy_cleanup(curl);

    return 0;
}

int lewei_update_value(int gateway_num, const char* userkey, const char* device_name, int value)
{
    char new_data[LEWEI_POST_DATA_MAX_LEN] = {0};

    lewei_format_data(new_data, LEWEI_POST_DATA_MAX_LEN, device_name, value);

    lewei_do_post(gateway_num, userkey, new_data, strlen(new_data));

    return 0;
}
